<script setup lang="tsx">
import { Dialog } from '@/components/Dialog'
import { Form, FormSchema } from '@/components/Form'
import { ElTree, ElMessage } from 'element-plus'

import { ref, computed, nextTick } from 'vue'
import { getRoleMenuApi, bindRoleApi } from '@/api/systemSettings/roleManage'

const visible = ref(false)
const disabled = ref(false)

let roleId
const dataList = ref([])
const treeRef = ref()

const schema = computed<FormSchema[]>(() => [
  {
    field: 'name',
    label: '权限',
    formItemProps: {
      slots: {
        default: () => {
          return (
            <ElTree
              ref={treeRef}
              class="w-full"
              showCheckbox
              nodeKey="id"
              props={{
                label: 'name'
              }}
              data={dataList.value}
            />
          )
        }
      }
    }
  }
])

const onFormSubmit = async () => {
  try {
    disabled.value = true
    loading.value = true
    // const menuIds_set = new Set()
    // const buttonIds_set = new Set()
    // const checkedNodes = treeRef.value.getCheckedNodes(false, true)
    // if (checkedNodes.length > 0) {
    //   // 过滤出菜单
    //   checkedNodes.forEach((node) => {
    //     if (node.parentId && node.parentId.startsWith('m_')) {
    //       menuIds_set.add(node.parentId.replace('m_', ''))
    //     }
    //     if (node.id.startsWith('m_')) {
    //       menuIds_set.add(node.id.replace('m_', ''))
    //     } else if (node.id.startsWith('b_')) {
    //       buttonIds_set.add(node.id.replace('b_', ''))
    //     }
    //   })
    // }
    // const menuIds = Array.from(menuIds_set).join(',')
    // const buttonIds = Array.from(buttonIds_set).join(',')
    // await bindRoleApi({ roleId, menuIds, buttonIds })
    disabled.value = false
    loading.value = true
    ElMessage.success('操作成功！')
    visible.value = false
  } catch (error) {
    console.log(error)
    disabled.value = false
    loading.value = true
  }
}

// 过滤选中
const filterCheckedKeys = (list) => {
  return list.reduce((prev, next) => {
    if (next.children && next.children.length) {
      return [...prev, ...filterCheckedKeys(next.children)]
    }
    if (next.checked) {
      return [...prev, next.id]
    }
    return prev
  }, [])
}

const loading = ref(false)
const open = async (id) => {
  visible.value = true
  loading.value = true
  try {
    const { data } = await getRoleMenuApi({ roleId: id, sysType: 1 })
    roleId = id
    dataList.value = data
    nextTick(() => {
      treeRef.value.setCheckedKeys(filterCheckedKeys(data))
    })
    loading.value = false
  } catch (error) {
    console.log(error)
    loading.value = false
  }
}

defineExpose({
  open
})
</script>

<template>
  <Dialog v-model="visible" title="设置权限" width="500">
    <div v-loading="loading">
      <Form class="w-[400px] ml-[auto] mr-[auto]" :schema="schema" :isCol="false" />
    </div>
    <template #footer>
      <div class="text-center mb-[16px]">
        <BaseButton
          type="primary"
          :loading="disabled"
          :disabled="disabled"
          debounce
          @click="onFormSubmit"
          >确认</BaseButton
        >
      </div>
    </template>
  </Dialog>
</template>
